package com.health.framework.interceptor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.ralasafe.Ralasafe;
import org.ralasafe.privilege.Privilege;

import com.health.common.Constants;
import com.health.framework.model.Menu;
import com.health.framework.model.MenuItem;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthorizeInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 3576864464423996527L;

    @Override
    public String intercept(ActionInvocation inv) throws Exception {

        Map<String, Object> session = inv.getInvocationContext().getSession();

        org.ralasafe.user.User user = (org.ralasafe.user.User) session.get(Constants.Session.SAFE_USER);

        if (null == user) {
            return Action.LOGIN;
        } else {
            List<Menu> menus = getMenu(Ralasafe.getBusinessPrivilegeTree(user));
            session.put(Constants.Session.MENUS, menus);
        }
        return inv.invoke();
    }

    // Privilege rootPvlg = Ralasafe.getBusinessPrivilegeTree(user);

    /**
     * 目前只支持两级菜单
     * 
     * @param rootPvlg
     * @return
     */
    @SuppressWarnings("rawtypes")
    private List<Menu> getMenu(Privilege rootPvlg) {
        List<Menu> menus = new ArrayList<Menu>();

        Collection children = rootPvlg.getChildren();
        if (children != null) {
            for (Iterator iter = children.iterator(); iter.hasNext();) {
                Privilege pvlg = (Privilege) iter.next();
                
                if (pvlg.getId() < 0) {
                    continue;
                }

                Menu menu = new Menu();
                menu.setId(pvlg.getId());
                menu.setName(pvlg.getName());

                if (!pvlg.getIsLeaf()) {
                    Collection subChild = pvlg.getChildren();
                    for (Iterator subIter = subChild.iterator(); subIter.hasNext();) {
                        Privilege subPvlg = (Privilege) subIter.next();
                        if (subPvlg.getIsLeaf()) {
                            MenuItem item = new MenuItem();
                            item.setId(subPvlg.getId());
                            item.setParentId(subPvlg.getPid());
                            item.setName(subPvlg.getName());
                            item.setUrl(subPvlg.getUrl());
                            item.setTarget(subPvlg.getTarget());

                            menu.addMenuItem(item);
                        }
                    }
                }
                menus.add(menu);
            }
        }
        return menus;
    }

}
